package book.controller;

import book.contant.SessionContent;
import book.model.Result;
import book.model.UserInfo;
import book.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 登录接口
     * 登录成功返回空字符串
     *  失败返回错误信息
     */
    @RequestMapping("/login")
    public Result login(String name, String password, HttpSession httpSession){
        //1.数据校验
        if(!StringUtils.hasLength(name) ||
            !StringUtils.hasLength(password)){
            return Result.nologin("用户名或密码为空!");
        }

        UserInfo userInfo=new UserInfo();
        userInfo.setUserName(name);
        UserInfo userInfo1 = userService.login(userInfo);
        if(userInfo1==null){
            return Result.fild("用户名不存在!");
        }else if(userInfo1.getPassword().equals(password)){
//            保存Session
            httpSession.setAttribute(SessionContent.USER_SESSION_KEY,userInfo);
//            登录成功返回 空
            return Result.success("");
        }else{
            return Result.fild("密码有误!");
        }
    }
}
